import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { anyRoutes, resetRouter, asyncRoutes, constantRoutes } from '@/router'
import { RouterLinkStub } from '@vue/test-utils'
// import { reject } from 'core-js/fn/promise'
import router from '@/router';
import cloneDeep from 'lodash/cloneDeep'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    routes: [],
    buttons: [],
    resultAsyncRoutes: [],
    resultAllRoutes: []

  }
}

const state = getDefaultState()

const mutations = {
  //重置state
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  //存储用户信息
  SET_USERINFO: (state, data) => {
    state.avatar = data.avatar
    state.buttons = data.buttons
    state.routes = data.routes
    state.name = data.name
    state.role = data.roles

  },
  // 重新赋值路由
  SET_RESULTASYNCROUTES: (state, asyncRoutes) => {
    state.resultAsyncRoutes = asyncRoutes
    state.resultAllRoutes = constantRoutes.concat(state.resultAsyncRoutes, anyRoutes)
    router.addRoutes(state.resultAllRoutes)
  }

}

const actions = {
  // user login
  //!!自己写的代码  这种使用了语法糖 async 和await  更简洁了 
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    let result = await login({ username: username.trim(), password: password })
    console.log(result, '登录业务')
    if (result.code == 20000) {
      const { data } = result
      commit('SET_TOKEN', data.token)
      setToken(data.token)
      return "ok"
    }
    else {
      return Promise.reject(new Error('failed'))
    }
    //!!作者自己写的代码
    /*    return new Promise((resolve, reject) => {
         login({ username: username.trim(), password: password }).then(response => {
           const { data } = response
           commit('SET_TOKEN', data.token)
           setToken(data.token)
           resolve()
         }).catch(error => {
           reject(error)
         })
       }) */
  },

  // get user info  得到用户的信息 用来判断权限问题
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        commit("SET_USERINFO", data)
        // console.log(response, 123232434)
        commit('SET_RESULTASYNCROUTES', computedAsyncRoutes(asyncRoutes, data.routes))
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}
// 找到需要的异步路由  用了函数的递归
const computedAsyncRoutes = (asyncRoutes, routes) => {
  return asyncRoutes.filter((item) => {
    // console.log(item)
    if (routes.includes(item.name)) {
      if (item.children && item.children.length) {
        item.children = computedAsyncRoutes(item.children, routes)
      }
      return true
    }
  })
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

